//
//  WXPInputOldCardInfoVC.m
//  MexicoLoan
//
//  Created by WXP on 2025/3/11.
//
//

#import "WXPInputOldCardInfoVC.h"
#import "WXPInputNewCardInfoVC.h"
#import "WXPFaceCameraVC.h"
#import "WXPWebLivenessVC.h"
#import "WXPLivenessFailView.h"

@interface WXPInputOldCardInfoVC ()

@property (nonatomic, strong) WXPNavView * navView;

@property (nonatomic, strong) UIView * viewContent;
@property (nonatomic, strong) UILabel * labelTitle;
@property (nonatomic, strong) UIView * viewTFBack;
@property (nonatomic, strong) UITextField * tfBankCard;
@property (nonatomic, strong) UILabel * labelError;
@property (nonatomic, strong) UIButton * btnSubmit;

@property (nonatomic, strong) WXPCommonAgreementView * agreementView;

@property (nonatomic, strong) WXPLivenessFailView * livenessFailView;
@property (nonatomic,   copy) NSString * livenChannel;

@end

@implementation WXPInputOldCardInfoVC

#pragma mark - lazy
- (WXPNavView *)navView
{
    if (_navView == nil) {
        _navView = [WXPNavView new];
        [_navView resetViewWithTitle:@"Modificar su cuenta bancaria"];
        _navView.leftTop = XY(0, 0);
    }
    return  _navView;
}
- (WXPCommonAgreementView *)agreementView{
    if (!_agreementView) {
        _agreementView = [WXPCommonAgreementView new];
        _agreementView.centerXBottom = XY(SCREEN_WIDTH/2, SCREEN_HEIGHT-LEFT_MARDIN);
    }
    return _agreementView;
}
- (UIView *)viewContent{
    if (!_viewContent) {
        _viewContent = [UIView new];
        _viewContent.userInteractionEnabled = true;
        _viewContent.backgroundColor = COLOR_WHITE;
        [GlobalMethod setRoundView:_viewContent color:[UIColor clearColor] numRound:16 width:0];
    }
    return _viewContent;
}
- (UILabel *)labelTitle{
    if (_labelTitle == nil) {
        _labelTitle = [UILabel new];
        _labelTitle.textColor = COLOR_BLACK;
        _labelTitle.fontNum = 12;
    }
    return _labelTitle;
}
- (UIView *)viewTFBack{
    if (_viewTFBack == nil) {
        _viewTFBack = [UIView new];
        _viewTFBack.backgroundColor = COLOR_WHITE;
        [GlobalMethod setRoundView:_viewTFBack color:COLOR_LINE numRound:16 width:1];
    }
    return _viewTFBack;
}
- (UITextField *)tfBankCard{
    if (_tfBankCard == nil) {
        _tfBankCard = [UITextField new];
        _tfBankCard.font = [UIFont systemFontOfSize: 14];
        _tfBankCard.textColor = COLOR_BLACK;
        _tfBankCard.borderStyle = UITextBorderStyleNone;
        _tfBankCard.keyboardType = UIKeyboardTypePhonePad;
        _tfBankCard.backgroundColor = [UIColor whiteColor];
        _tfBankCard.delegate = self;
        _tfBankCard.placeholder = @"Por favor escribe";
        [_tfBankCard addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    }
    return _tfBankCard;
}
- (UILabel *)labelError{
    if (_labelError == nil) {
        _labelError = [UILabel new];
        _labelError.textColor = COLOR_RED;
        _labelError.fontNum = 12;
        _labelError.numberOfLines = 0;
        _labelError.lineSpace = 3;
    }
    return _labelError;
}
- (UIButton *)btnSubmit{
    if (_btnSubmit == nil) {
        _btnSubmit = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnSubmit.backgroundColor = COLOR_PRIMARY;
        [_btnSubmit setTitleColor:COLOR_BLACK forState:UIControlStateNormal];
        _btnSubmit.titleLabel.font = [UIFont systemFontOfSize:14];
        _btnSubmit.widthHeight = XY(0, BUTTON_HEIGHT);
        _btnSubmit.userInteractionEnabled = false;
        _btnSubmit.alpha = 0.5;
        [GlobalMethod setRoundView:_btnSubmit color:[UIColor clearColor] numRound:BUTTON_HEIGHT/2 width:0];
        [_btnSubmit setTitle:@"Enviar" forState:(UIControlStateNormal)];
        WEAKSELF
        [_btnSubmit setNoRepeatActionWithInterval:3 action:^(UIButton * _Nonnull button) {
            [NSObject clickFeedback];
            [weakSelf.btnSubmit addClickAnimate];
            [weakSelf requestCheckOldBankCard];
        }];
    }
    return _btnSubmit;
}
- (WXPLivenessFailView *)livenessFailView
{
    if (_livenessFailView == nil) {
        _livenessFailView = [WXPLivenessFailView  new];
    }
    return  _livenessFailView;
}

#pragma mark - viewDidLoad
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_CheckBankCard action:KEY_Enter extInfo:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
}

- (void)configUI{
    self.view.backgroundColor = COLOR_BACKGROUND;
    self.viewBG.backgroundColor = COLOR_BACKGROUND;
    self.tableHeaderTopBg.backgroundColor = [UIColor clearColor];
    self.tableView.backgroundColor = COLOR_WHITE;
    UITapGestureRecognizer * tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
    [self.tableView addGestureRecognizer:tapGestureRecognizer];
    [self.view addSubview:self.navView];
    [self.view addSubview:self.agreementView];
    
    self.tableView.height = self.agreementView.top-10-self.navView.bottom-10;
    self.tableView.width = SCREEN_WIDTH-2*LEFT_MARDIN;
    [GlobalMethod setRoundView:self.tableView color:COLOR_WHITE numRound:16 width:0];
    self.tableView.centerXTop = XY(SCREEN_WIDTH/2, self.navView.bottom+10);
    
    self.viewContent.widthHeight = XY(self.tableView.width, 0);
    
    [self.labelTitle fitTitle:@"Número de cuenta CLABE o tarjeta bancaria original " variable:SCREEN_WIDTH-LEFT_MARDIN*4];
    self.labelTitle.leftTop = XY(15, 20);
    [self.viewContent addSubview:self.labelTitle];
    
    self.viewTFBack.widthHeight = XY(SCREEN_WIDTH-LEFT_MARDIN*4, Ratio(44));
    self.viewTFBack.centerXTop = XY(self.viewContent.width/2, self.labelTitle.bottom+16);
    [self.viewContent addSubview:self.viewTFBack];
    
    self.tfBankCard.widthHeight = XY(self.viewTFBack.width-LEFT_MARDIN*2, self.viewTFBack.height-10);
    self.tfBankCard.leftCenterY = XY(self.viewTFBack.left+LEFT_MARDIN, self.viewTFBack.centerY);
    [self.viewContent addSubview:self.tfBankCard];
    
    // El número de cuenta CLABE o tarjeta bancaria original no es válido, por favor introdúzcalo de nuevo.
    
    // *El número de tarjeta ha sido ingresado incorrectamente 3 veces hoy, la tarjeta no puede ser cambiada temporalmente, por favor intente nuevamente mañana.
    
    [self.viewContent addSubview:self.labelError];
    self.labelError.hidden = true;
    
    self.btnSubmit.width = self.viewTFBack.width;
    self.btnSubmit.centerXTop = XY(self.viewContent.width/2, self.viewTFBack.bottom+100);
    [self.viewContent addSubview:self.btnSubmit];
    
    self.viewContent.height = self.btnSubmit.bottom+26;
    self.tableView.tableHeaderView = self.viewContent;
}

#pragma mark - 收键盘
- (void)tapClick:(UITapGestureRecognizer * )tap{
    [self.view endEditing:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView{
    [self.view endEditing:YES];
}

#pragma mark - textFieldDidChange
- (void)textFieldDidChange:(UITextField *)textField{
    self.btnSubmit.userInteractionEnabled = isStr(textField.text);
    self.btnSubmit.alpha = isStr(textField.text) ? 1 : 0.5;
}

#pragma mark -  跳转事件
// 跳转去活体拍照
- (void)jumpToLivenessTakePhoto{
    WEAKSELF
    WXPFaceCameraVC * vc = [WXPFaceCameraVC new];
    vc.liveType = 3;
    vc.livenChannelEnum = KEY_SILENCE_LIVENESS;
    vc.liveTypeEnum = KEY_MODIFY_BANK_CARD_LIVE;
    vc.blockUploadSuccess = ^(NSString *url, NSString *photoName, NSString *livenessId) {
        //检查修改银行卡活体接口
        [weakSelf requestCheckModifyBankCardLiveWithPhotoName:photoName livenessId:livenessId];
    };
    vc.blockUploadFail = ^(NSString * errorStr) {
        [GlobalMethod hitPointWithPageName:KEY_ChangeBankFacial action:KEY_Liveness_Failure extInfo:@{@"errorMsg":errorStr}];
        [weakSelf.view addSubview:weakSelf.livenessFailView];
    };
    [Global_Nav pushViewController:vc animated:true];
}

// 跳转去H5活体拍照
- (void)jumpToLivenessH5{
    WXPWebLivenessVC * vc = [WXPWebLivenessVC new];
    vc.liveTypeEnum = KEY_MODIFY_BANK_CARD_LIVE;
    WEAKSELF
    vc.blockUploadSuccess = ^(NSString *url, NSString *photoName, NSString *livenessId) {
        //检查修改银行卡活体接口
        [weakSelf requestCheckModifyBankCardLiveWithPhotoName:photoName livenessId:livenessId];
    };
    vc.blockUploadFail = ^(NSString * errorStr) {
        [GlobalMethod hitPointWithPageName:KEY_ChangeBankFacial action:KEY_Liveness_Failure extInfo:@{@"errorMsg":errorStr}];
    };
    [Global_Nav pushViewController:vc animated:true];
}

#pragma mark - request
// 校验- 原银行卡
- (void)requestCheckOldBankCard{
    [GlobalMethod hitPointWithPageName:KEY_CheckBankCard action:KEY_Click extInfo:@{@"bankNo": self.tfBankCard.text}];
    [RequestApi requestCheckOldBankCard:self.tfBankCard.text delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        [GlobalMethod hitPointWithPageName:KEY_CheckBankCard action:KEY_End extInfo:@{@"isSuccess": @"true", @"errorMsg": @""}];
        self.labelError.hidden = true;
        
        if(self.needLiveness){
            // 需要 活体验证
            // 检查是否可以做某项授权接口
            [self requestAuthCheckWithAuthType];
        }else{
            // 直接 跳转修改银行卡
            WXPInputNewCardInfoVC * vc = [WXPInputNewCardInfoVC new];
            vc.modelBankCard = self.bankCardModel;
            [Global_Nav pushViewController:vc animated:true];
        }
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        [self.labelError fitTitle:errorStr variable:self.viewTFBack.width];
        self.labelError.leftTop = XY(self.viewTFBack.left, self.viewTFBack.bottom+LEFT_MARDIN);
        self.labelError.hidden = false;
        [GlobalMethod hitPointWithPageName:KEY_CheckBankCard action:KEY_End extInfo:@{@"isSuccess": @"false", @"errorMsg": errorStr}];
    }];
}

// 检查用户是否可以做某项授权接口
- (void)requestAuthCheckWithAuthType{
    [RequestApi requestCheckUserCanAuthWithType:KEY_LIVENESS phone:@"" delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        if([response boolValueForKey:KEY_checkResult]){
            // true，调用 获取活体渠道
            WEAKSELF
            [GlobalMethod isOpenCamearPermissionsWithCompletion:^(BOOL granted) {
                [GlobalMethod mainQueueBlock:^{
                    if (granted){
                        [weakSelf requestAuthLivenConfig];
                    }
                }];
            }];
        }else{
            // 当接口返回‘false’时，弹窗提示
            [GlobalMethod showAlert:@"Lo sentimos. Aún no es la fecha del evento"];
        }
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}
// 获取活体渠道接口
- (void)requestAuthLivenConfig{
    [RequestApi requestNewAuthLivenConfigWithPhone:@"" delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        // false：根据返回的参数值进行判断
        if (isStr([response stringValueForKey:KEY_SILENCE_LIVENESS])){
            [GlobalMethod hitPointWithPageName:KEY_ChangeBankFacial action:KEY_Liveness_Do extInfo:@{@"livenChannel": @"SILENCE_LIVENESS"}];
            // SILENCE_LIVENESS不为null：跳转静默活体页开始做静默活体拍照
            // 先验证相机，验证成功再去拍照
            self.livenChannel = KEY_SILENCE_LIVENESS;
            [self jumpToLivenessTakePhoto];
        }else if (isStr([response stringValueForKey:KEY_CLOUDUN_H5_V3])){
            [GlobalMethod hitPointWithPageName:KEY_ChangeBankFacial action:KEY_Liveness_Do extInfo:@{@"livenChannel": @"KEY_CLOUDUN_H5_V3"}];
            // CLOUDUN_H5_V3不为null：跳转LivenessH5 SDK-2活体进行识别
            self.livenChannel = KEY_CLOUDUN_H5_V3;
            //[GlobalMethod userBehaviorRecordWithPageName:@"ChangeBankFacial" action:@"Liveness_Do" extInfo:@{@"livenChannel":@"CLOUDUN_H5_V3"}];
            [self jumpToLivenessH5];
        }
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}
// 检查修改银行卡活体接口
- (void)requestCheckModifyBankCardLiveWithPhotoName:(NSString *)photoName livenessId:(NSString *)livenessId{
    [RequestApi requestCheckModifyBankCardLiveWithLivenChannelEnum:self.livenChannel livenessId:livenessId livenessImg:photoName delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        [GlobalMethod hitPointWithPageName:KEY_ChangeBankFacial action:KEY_Liveness_Success extInfo:nil];
        WXPInputNewCardInfoVC * vc = [WXPInputNewCardInfoVC new];
        vc.modelBankCard = self.bankCardModel;
        [Global_Nav pushViewController:vc animated:true];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        [GlobalMethod hitPointWithPageName:KEY_ChangeBankFacial action:KEY_Liveness_Failure extInfo:@{@"livenessId":livenessId, @"errorMsg": errorStr}];
    }];
}


@end
